package ua.org.nuos.sdms.clientgui.client.view.selectGroup;

import com.vaadin.ui.*;
import ua.org.nuos.sdms.clientgui.client.components.factory.ButtonFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.LayoutFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.SeparatorFactory;
import ua.org.nuos.sdms.clientgui.client.components.factory.WindowFactory;
import ua.org.nuos.sdms.clientgui.client.controller.GlobalBoard;
import ua.org.nuos.sdms.clientgui.client.events.AttachUserToGroupEvent;
import ua.org.nuos.sdms.clientgui.client.events.BackToSearchGroupEvent;
import ua.org.nuos.sdms.clientgui.client.util.DescriptionBuilder;
import ua.org.nuos.sdms.clientgui.server.AppProxy;
import ua.org.nuos.sdms.middle.entity.Group;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: dio
 * Date: 08.03.12
 * Time: 17:34
 * To change this template use File | Settings | File Templates.
 */
public class SearchResultComponent extends VerticalLayout {

    public static final String ID = SearchResultComponent.class.getSimpleName();

    private List<Group> groups;

    public SearchResultComponent(List<Group> groups) {
        this.groups = groups;
        init();
    }

    private void init() {
        setSizeFull();
        AppProxy.getInstance().getComponentLocator().addContainer(ID, this);

        if (groups.isEmpty()) {
            Label message = new Label("Вы не состоите не в одной группе." +
                    "<br />Вступите в группу либо создайте новую.");
            message.setContentMode(Label.CONTENT_XHTML);
            addComponent(message);
        } else {
            Panel panel = new Panel();
            panel.setStyleName("borderless light");
            panel.setScrollable(true);
            panel.setSizeFull();
            for (Group group : groups) {
                Button button = createGroupButton(group);
                panel.addComponent(button);
                panel.addComponent(SeparatorFactory.getHorizontal());
            }
            addComponent(panel);
            setExpandRatio(panel, 1.f);
        }

        Layout buttons = getButtonsLayout();
        addComponent(buttons);
        setComponentAlignment(buttons, Alignment.BOTTOM_RIGHT);
    }

    private Layout getButtonsLayout() {
        Button close = WindowFactory.getCloseButton(
                AppProxy.getInstance().getComponentLocator().getWindow(SelectGroupWindow.ID).getWindow(), "Не стоит");
        Button back = ButtonFactory.getButton("Назад", GlobalBoard.ID, new BackToSearchGroupEvent());
        return LayoutFactory.getHLayout(back, close);
    }

    private Button createGroupButton(Group g) {
        Button b = ButtonFactory.getButton(g.getName(), GlobalBoard.ID, new AttachUserToGroupEvent(g));
        b.setStyleName("borderless");
        b.addStyleName("button_b_caption");
        b.setDescription(DescriptionBuilder.buildGroupDescription(g));
        return b;
    }
}
